<template>
  <div class="login-container container">
    <h2>登录</h2>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="account"
        label="账号"
        @input="errorMessage = null"
        placeholder="手机号或邮箱"
        :rules="[{ required: true, message: '请填写登录所需账号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="pswd"
        label="密码"
        placeholder="密码"
        :error-message="errorMessage"
        @input="errorMessage = null"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
            message: '密码需要由字母+数字组成且8-20位组成'
          }
        ]"
      />
      <div class="submit">
        <van-button round block type="info" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <div class="bottom-link">
      <nuxt-link to="/find/password">找回密码</nuxt-link>
      <nuxt-link to="/register">注册</nuxt-link>
    </div>
  </div>
</template>
<script>
import { COOKIE_TOKEN } from "~/common";
export default {
  layout: "notabbar",
  data() {
    return {
      username: "",
      password: "",
      errorMessage: null,
      path: "/"
    };
  },
  methods: {
    onSubmit(values) {
      this.$apiLogin(values).then(res => {
        const { status, msg, data, token } = res;
        if (status === 0) {
          this.$toast({ message: msg, type: "success" });
          this.$saveUserInfo(data, token);
          setTimeout(() => {
            this.$router.replace(this.path);
          }, 1500);
          return;
        }
        this.errorMessage = msg;
      });
    }
  },
  mounted() {
    const path = this.$route.query.path || "/";
    this.path = path;
    this.$rmStorageData(true, COOKIE_TOKEN);
    this.$rmCookie(COOKIE_TOKEN);
    this.$store.commit("setToken", null);
  }
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
